<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!-- 搜索栏 -->
      <div
        style="display: flex; justify-content: left"
        v-if="userName == 'operation'"
      >
        <el-input
          v-model="searchList.id"
          placeholder="请输入商户ID"
          style="width: 250px; margin-right: 20px"
          size="small"
          :clearable="true"
          @keyup.enter.native="searchFn"
        />
        <!--搜索与重置-->
        <div>
          <el-button
            class="filter-item"
            size="mini"
            type="success"
            icon="el-icon-search"
            @click="searchFn"
            >搜索</el-button
          >
          <el-button
            class="filter-item"
            size="mini"
            type="warning"
            icon="el-icon-refresh-left"
            @click="resetFn"
            >重置</el-button
          >
        </div>
      </div>

      <!-- 新增---导出 -->
      <div style="margin-top: 10px">
        <el-button
          v-if="userName == 'operation'"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="newFn"
        >
          新增
        </el-button>
        <!-- <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="AddBatteryFn"
        >
          商户添加电池
        </el-button>
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="AddBatteryFn1"
        >
          批量导入商户电池
        </el-button> -->
      </div>
    </div>
    <!--Form编辑表单-->
    <el-dialog :visible.sync="isEdit" :title="FormTitle" width="500px">
      <el-form
        ref="form"
        :inline="false"
        :model="formList"
        :rules="formRules"
        size="medium"
        label-width="120px"
      >
        <el-form-item label="商户名称" prop="merchant_name">
          <el-input
            v-model="formList.merchant_name"
            placeholder="请输入"
            style="width: 320px"
          />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
            v-model="formList.phone"
            placeholder="请输入"
            style="width: 320px"
          />
        </el-form-item>
        <el-form-item label="电池回调地址" prop="notify_url">
          <el-input
            v-model="formList.notify_url"
            placeholder="请输入"
            style="width: 320px"
          />
        </el-form-item>
        <el-form-item label="登陆用户名" prop="login_name" v-if="!formList.id">
          <el-input
            v-model="formList.login_name"
            placeholder="请输入"
            style="width: 320px"
          />
        </el-form-item>
        <el-form-item label="密码" prop="passwd" v-if="!formList.id">
          <el-input
            v-model="formList.passwd"
            placeholder="请输入"
            style="width: 320px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isEdit = false" type="text">取消</el-button>
        <el-button
          :loading="formLoading"
          type="primary"
          @click="editConfirmFn('form')"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      :data="list"
      :header-cell-style="{ 'text-align': 'center', color: '#000' }"
      :cell-style="{ 'text-align': 'center' }"
      :highlight-current-row="true"
      :border="true"
      style="width: 100%"
      height="620"
    >
      <el-table-column :show-overflow-tooltip="true" prop="id" label="商户ID" />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="merchant_name"
        label="商户名称"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="phone"
        label="电话"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="notify_url"
        label="电池回调地址"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="api_key"
        label="商户密钥"
      />
      <el-table-column
        label="操作"
        width="150px"
        align="center"
        v-if="userName == 'merchant'"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            style="color: #fff"
            @click="compileFn(scope.row)"
            >编辑</el-button
          >
          <el-popover
            :ref="scope.row.id"
            placement="top"
            width="140"
            v-if="false"
          >
            <p>确定删除该条数据？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="$refs[scope.row.id].doClose()"
                >取消</el-button
              >
              <el-button
                :loading="delLoading"
                type="primary"
                size="mini"
                @click="delMethod(scope.row.id)"
                >确定</el-button
              >
            </div>
            <el-button
              slot="reference"
              type="danger "
              size="mini"
              style="color: #fff"
              >删除</el-button
            >
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      :page-size.sync="page.size"
      :page-sizes="[5, 10, 20, 30, 50]"
      :total="page.total"
      :current-page.sync="page.page"
      style="margin-top: 8px"
      layout="total,sizes, prev, pager, next, jumper"
      @size-change="sizeChangeFn"
      @current-change="currentChangeFn"
    />
    <!-- 添加电池模态框 -->
    <el-dialog
      :visible.sync="uploadFile_fag"
      title="给商户添加电池"
      width="500px"
    >
      <el-form
        ref="Mbattery"
        :inline="false"
        :model="MbatteryList"
        :rules="MbatteryRules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="添加电池" prop="battery_id">
          <el-input
            v-model="MbatteryList.battery_id"
            placeholder="请输入电池编号,如有多个，请用逗号'，'隔开"
            type="textarea"
            :clearable="true"
            style="width: 260px"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadFile_fag = false" type="text">取消</el-button>
        <el-button type="primary" @click="MbatteryConfirmFn('Mbattery')"
          >确认</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="批量导入商户电池"
      :visible.sync="uploadFile_fag1"
      width="30%"
    >
      <div class="content" style="text-align: center">
        <el-upload
          class="upload-demo"
          ref="uploadBattery"
          action="#"
          :show-file-list="true"
          :limit="1"
          :on-exceed="handleExceed"
          :http-request="httpRequest"
        >
          <div style="display: flex; justify-content: center">
            <el-button
              style="margin-right: 30px"
              slot="trigger"
              size="small"
              type="primary"
              >选取文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传 xlsx 和 xls 格式
            </div>
          </div>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { urlObj } from "@/api/login";
export default {
  data() {
    return {
      // 控制添加电池模态框   start
      uploadFile_fag1: false, //控制添加电池模态框的显示隐藏
      fileList: [],

      uploadFile_fag: false,
      MbatteryList: {},
      MbatteryRules: {
        battery_id: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      // 控制添加电池模态框  end
      searchList: {
        id: "",
      }, // 搜索数据
      isEdit: false, //控制编辑表单打开与否
      FormTitle: "", //编辑表单标题
      formLoading: false, //编辑确认状态--加载与否
      formList: {
        //编辑表单数据
        id: "",
        merchant_name: "",
        phone: "",
        notify_url: "",
        login_name: "",
        passwd: "",
      },
      formRules: {
        //编辑表单规则
        merchant_name: [{ required: true, message: "请输入", trigger: "blur" }],
        // phone: [{ required: true, message: "请输入", trigger: "blur" }],
        // notify_url: [{ required: true, message: "请输入", trigger: "blur" }],
        login_name: [{ required: true, message: "请输入", trigger: "blur" }],
        passwd: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      list: [], //列表数据
      delLoading: false, //删除状态--加载与否
      page: {
        size: 10, //每页的数量
        page: 1, //当前页
        total: 0, //总数
      }, //分页
      userName: "", //获取角色名称
    };
  },
  mounted() {
    this.userName =
      JSON.parse(sessionStorage.getItem("userObj")).user_type || "";
    if (this.userName == "merchant") {
      this.listFn(JSON.parse(sessionStorage.getItem("userObj")).mer_id);
    } else {
      this.listFn();
    }
  },
  methods: {
    // 分页---每页的数量
    sizeChangeFn(val) {
      console.log("每页的数量：", val);
      this.page.page = 1;
      this.page.size = val;
      this.listFn();
    },
    // 当前页数
    currentChangeFn(val) {
      console.log("当前页数：", val);
      this.page.pege = val;
      this.listFn();
    },
    // 重置
    resetFn() {
      console.log("重置");
      this.searchList.id = "";
      this.listFn();
    },
    // 搜索
    searchFn() {
      console.log("搜索", this.searchList.id);
      this.listFn(this.searchList.id);
    },
    // 新增
    newFn() {
      this.isEdit = true;
      this.FormTitle = "新增商户";
      this.formList.id = "";
      this.formList.merchant_name = "";
      this.formList.phone = "";
      this.formList.notify_url = "";
      this.formList.login_name = "";
      this.formList.passwd = "";
    },
    // 列表编辑按钮
    compileFn(row) {
      this.isEdit = true;
      this.FormTitle = "编辑商户";
      this.formList.id = row.id;
      this.formList.merchant_name = row.merchant_name;
      this.formList.phone = row.phone;
      this.formList.notify_url = row.notify_url;
    },
    // 列表编辑按钮 --确定
    editConfirmFn(val) {
      let prarms = {
        func: this.formList.id ? "setMerchant" : "createMerchant",
        token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
        business: this.formList,
      };
      this.$refs[val].validate(async (valid) => {
        if (valid) {
          this.formLoading = true;
          urlObj(prarms)
            .then((res) => {
              if (this.userName == "merchant") {
                this.listFn(
                  JSON.parse(sessionStorage.getItem("userObj")).mer_id
                );
              } else {
                this.listFn();
              }
              this.$message({
                message: res.msg || "",
                type: res.code == 0 ? "success" : "error",
              });
            })
            .catch((error) => {
              this.$message({
                message: res.msg || "",
                type: "error",
              });
            });
          this.formLoading = false;
          this.isEdit = false;
        }
      });
    },
    // 列表数据
    listFn(id) {
      let prarms = {
        func: "getMerchants",
        token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
        business: { id: id ? id : "" },
      };
      urlObj(prarms)
        .then((res) => {
          // console.log(666, res);
          this.list = res.result;
          this.page.total = res.count || res.result.length;
        })
        .catch((error) => {});
    },
    // 删除按钮
    delMethod(id) {
      this.delLoading = true;
      let prarms = {
        func: "delStation",
        token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
        business: { id: id },
      };
      urlObj(prarms)
        .then((res) => {
          this.listFn();
          this.$message({
            message: res.msg || "",
            type: res.code == 0 ? "success" : "error",
          });
        })
        .catch((error) => {
          this.$message({
            message: res.msg || "",
            type: "error",
          });
        });
      this.delLoading = false;
      this.$refs[id].doClose();
    },

    // 商户添加电池---模态框  start
    // 商户添加电池
    AddBatteryFn() {
      this.uploadFile_fag = true;
    },
    // 商户添加电池---模态框 确认
    MbatteryConfirmFn(val) {
      let batteries_ids = this.MbatteryList.battery_id;
      let batteries_idsList = [];
      if (batteries_ids.includes(",")) {
        batteries_idsList = batteries_ids.split(",");
      } else if (batteries_ids.includes("，")) {
        batteries_idsList = batteries_ids.split("，");
      } else {
        batteries_idsList = [batteries_ids];
      }

      let prarms = {
        func: "setBatteryMerchant",
        token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
        business: {
          battery_id: batteries_idsList || [], //电池编号
          excel_file: "", //excel文件
        },
      };

      this.$refs[val].validate(async (valid) => {
        if (valid) {
          urlObj(prarms)
            .then((res) => {
              this.listFn();
              this.$message({
                message: res.msg || "",
                type: res.code == 0 ? "success" : "error",
              });
            })
            .catch((error) => {
              this.$message({
                message: res.msg || "",
                type: "error",
              });
            });
          this.uploadFile_fag = false;
          this.MbatteryList.battery_id = "";
        }
      });
    },

    AddBatteryFn1() {
      this.uploadFile_fag1 = true;
    },
    //这个file参数 也就是文件信息，你使用 插件 时 你就可以打印出文件信息 看看嘛
    getBase64(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let fileResult = "";
        reader.readAsDataURL(file); //开始转
        reader.onload = function () {
          fileResult = reader.result;
        }; //转 失败
        reader.onerror = function (error) {
          reject(error);
        }; //转 结束  咱就 resolve 出去
        reader.onloadend = function () {
          resolve(fileResult);
        };
      });
    },
    //文件超出个数限制时的钩子
    handleExceed(file, fileList) {
      // console.log('文件超出个数限制时的钩子', file, fileList);
      this.$message({
        message: "只能上传一个文件",
        type: "error",
      });
    },
    httpRequest(data) {
      // 没事儿就打印data看看呗　　　　//这是限制上传文件类型
      console.log(333, data);
      const isPFX =
        data.file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const isLt2M = data.file.size / 1024 / 1024 < 2;

      // if (!isPFX) {
      //   this.$message.error("上传文件只能是 XLSX 格式!");
      // } else
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 2MB!");
      } else {
        // 转base64
        this.getBase64(data.file).then((resBase64) => {
          // console.log(resBase64.split(",")[1]); //直接拿到base64信息
          let prarms = {
            func: "setBatteryMerchant",
            token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
            business: {
              battery_id: [], //电池编号
              excel_file: resBase64.split(",")[1] || "", //excel文件
            },
          };
          urlObj(prarms)
            .then((res) => {
              this.listFn();
              this.$message({
                message: res.msg || "",
                type: res.code == 0 ? "success" : "error",
              });
            })
            .catch((error) => {
              this.$message({
                message: res.msg || "",
                type: "error",
              });
            });
          this.uploadFile_fag1 = false;
        });
      }
    },
    // 商户添加电池---模态框  end
  },
};
</script>

<style lang="scss" scoped></style>
